package org.elec.mac.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elec.mac.entity.*;
import org.elec.mac.page.PageList;
import org.elec.mac.page.PageProperty;
import org.elec.mac.service.*;
import org.elec.mac.utils.JSONUtil;
import org.elec.mac.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@Slf4j
@Controller
public class MachineController extends BaseController {

    @Autowired
    private SMachineService sMachineService;

    @Autowired
    private SDeviceService sDeviceService;

    @Autowired
    private SMaterialService sMaterialService;

    @Autowired
    private SDeviceTechService sDeviceTechService;

    @Autowired
    private SMachineTechService sMachineTechService;

    @Autowired
    private SDeviceMaterialService sDeviceMaterialService;

    @Autowired
    private SMachineMaterialService  sMachineMaterialService;

    @Autowired
    private SBasicsFormulaService sBasicsFormulaService;

    @RequestMapping("/machine_list.do")
    public String machineListHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                     @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                     @RequestParam(value = "limit", required = false) String limit,
                                     @RequestParam(value = "page", required = false) String page) throws IOException {

        if ("page".equals(action)) {
            PageProperty pp = new PageProperty();
            Map<String, Object> map = new HashMap<String, Object>();
            try {
                this.setPageInfo(request.getCookies(), pp, limit, page);
                PageList<Map<String, Object>> lintPageList = sMachineService.getMachineInfoPageList(pp);
                map.put("success", true);
                map.put("records", lintPageList.getRecords());
                map.put("recordsTotal", lintPageList.getTotalRecords());
                map.put("recordsFiltered", lintPageList.getTotalRecords());
            } catch (Exception ex) {
                log.error("设备列表获取错误", ex);
                map.put("success", false);
                map.put("msg", "设备列表获取错误");
            }
            response.getWriter().write(JSONUtil.map2json(map));
            return null;
        }
        return "/machine/machine_list";
    }

    // 机台新增
    @RequestMapping(value = "/machine_add.do")
    public void machineAddHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                  @RequestParam(value = "action", required = false, defaultValue = "") String action) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if ("do".equals(action)) {
            try {
                String name = this.getParameter(request, "name");
                String sign = this.getParameter(request, "sign");
                String address = this.getParameter(request, "address");
                Long did = Utils.parseLong(this.getParameter(request, "did"), 0L);
                if (StringUtils.isBlank(name)) {
                    result.setSuccess(false);
                    result.setMsg("机台名不能为空");
                }
                if (result.isSuccess() && StringUtils.isBlank(address)) {
                    result.setSuccess(false);
                    result.setMsg("地址不能为空");
                }
                if (result.isSuccess() && did == 0L) {
                    result.setSuccess(false);
                    result.setMsg("设备不能为空");
                }
                if (result.isSuccess()) {
                    SMachine sMachine = new SMachine();
                    sMachine.setName(name);
                    sMachine.setSign(sign);
                    sMachine.setAddress(address);
                    sMachine.setLatitude(0L);
                    sMachine.setLongitude(0L);
                    sMachine.setDid(did);
                    sMachine.setCreateTime(new Date());
                    sMachine.setCreator(getSessionUsername(request));
                    sMachine.setModifyTime(new Date());
                    sMachine.setModifier(getSessionUsername(request));
                    sMachine.setStatus(true);
                    sMachine.setFlag(true);
                    sMachineService.insert(sMachine);
                    log.info("机台新增");
                    // 机台参数新增
                    Map<String, Object> param = new HashMap<String, Object>();
                    param.put("flag", 1);
                    param.put("did", did);
                    List<SDeviceTech> sDeviceTechList = sDeviceTechService.list(param);
                    if (sDeviceTechList != null && sDeviceTechList.size() > 0) {
                        this.insertMachineTech(sDeviceTechList, sMachine.getId());
                    }
                    log.info("机台参数新增");

                    //机台原料新增
                    List<SDeviceMaterial> deviceMaterials = sDeviceMaterialService.list(param);

                    for (SDeviceMaterial item : deviceMaterials) {
                        param.clear();
                        param.put("id", item.getMaid());
                        SMaterial sMaterial = sMaterialService.get(param);
                        Integer amount = 1;
                        //判断是基础配方还是原料
                        if(null != sMaterial) {
                            if(sMaterial.getSign() == 1) {
                                amount = sBasicsFormulaService.getMaterialAmount(sMaterial.getId());
                            }
                        }
                        SMachineMaterial machineMaterial = new SMachineMaterial();
                        machineMaterial.setMachid(sMachine.getId());
                        machineMaterial.setMid(item.getMaid());
                        machineMaterial.setAmount(amount);
                        machineMaterial.setWarning(1);
                        sMachineMaterialService.insert(machineMaterial);
                    }
                    log.info("机台原料新增");
                }


            } catch (Exception ex) {
                log.error("机台新增错误", ex);
                result.setSuccess(false);
                result.setMsg("机台新增错误");
            }
        }
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("flag", 1);
        List<SDevice> deviceList = sDeviceService.list(param);
        StringBuilder builder = new StringBuilder();
        if (deviceList != null && deviceList.size() > 0) {
            builder.append("<option value=\"\">---请选择---</option>");
            for (SDevice sDevice : deviceList) {
                builder.append("<option value=\"" + sDevice.getId() + "\">");
                builder.append(sDevice.getName());
                builder.append("</option>");
            }
        }
        result.getBody().put("deviceList", builder.toString());
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }

    // 机台修改
    @RequestMapping(value = "/machine_edit.do")
    public void machineEditHandler(HttpServletRequest request, HttpServletResponse response, ModelMap model,
                                   @RequestParam(value = "action", required = false, defaultValue = "") String action,
                                   @RequestParam(value = "id", required = false, defaultValue = "") String id) throws IOException {
        ExecuteResult result = new ExecuteResult();
        result.setSuccess(true);
        result.setMsg("成功");
        if ("edit".equals(action)) {
            try {
                Map<String, Object> params = new HashMap<>();
                params.put("id", Utils.parseLong(id, 0L));
                SMachine sMachine = sMachineService.get(params);
                params.clear();
                params.put("id", sMachine.getDid());
                String devicename = sDeviceService.get(params).getName();
                result.getBody().put("sMachine", sMachine);
                result.getBody().put("devicename", devicename);
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("flag", 1);
                List<SDevice> deviceList = sDeviceService.list(param);
                StringBuilder builder = new StringBuilder();
                if (deviceList != null && deviceList.size() > 0) {
                    builder.append("<option value=\"\">---请选择---</option>");
                    for (SDevice sDevice : deviceList) {
                        builder.append("<option value=\"" + sDevice.getId() + "\" ");
                        if (sDevice.getId() == sMachine.getDid()) {
                            builder.append("selected=\"selected\"");
                        }
                        builder.append(">");
                        builder.append(sDevice.getName());
                        builder.append("</option>");
                    }
                }
                result.getBody().put("deviceList", builder.toString());
                log.info("机台修改开启");
            } catch (Exception ex) {
                log.error("机台修改开启错误", ex);
                result.setSuccess(false);
                result.setMsg("机台修改开启错误");
            }
        }
        if ("doEdit".equals(action)) {
            try {
                Long poid = Utils.parseLong(id, 0L);
                String name = this.getParameter(request, "name");
                String sign = this.getParameter(request, "sign");
                String address = this.getParameter(request, "address");
                Long did = Utils.parseLong(this.getParameter(request, "editdevice"), 0L);
                if (result.isSuccess() && poid == 0L) {
                    result.setSuccess(false);
                    result.setMsg("机台ID不能为空");
                }
                if (result.isSuccess() && StringUtils.isBlank(name)) {
                    result.setSuccess(false);
                    result.setMsg("机台名不能为空");
                }
                if (result.isSuccess() && StringUtils.isBlank(address)) {
                    result.setSuccess(false);
                    result.setMsg("机台地址不能为空");
                }
                if (result.isSuccess() && did == 0L) {
                    result.setSuccess(false);
                    result.setMsg("设备不能为空");
                }
                if (result.isSuccess()) {
                    Map<String, Object> params = new HashMap<>();
                    params.put("id", poid);
                    SMachine sMachine = sMachineService.get(params);
                    //
                    SMachine po = new SMachine();
                    po.setId(poid);
                    po.setName(name);
                    po.setSign(sign);
                    po.setAddress(address);
                    po.setLatitude(0L);
                    po.setLongitude(0L);
                    po.setDid(did);
                    po.setModifyTime(new Date());
                    po.setModifier(getSessionUsername(request));
                    sMachineService.update(po);
                    log.info("机台修改");
                    // 用户选择其他设备类型
                    if (!sMachine.getDid().equals(did)) {
                        // 删除插入技术参数
                        params.clear();
                        params.put("machid", poid);
                        sMachineTechService.deleteMachineTech(params);
                        //
                        Map<String, Object> param = new HashMap<String, Object>();
                        param.put("flag", 1);
                        param.put("did", did);
                        List<SDeviceTech> sDeviceTechList = sDeviceTechService.list(param);
                        if (sDeviceTechList != null && sDeviceTechList.size() > 0) {
                            this.insertMachineTech(sDeviceTechList, poid);
                        }
                        log.info("机台参数修改");
                    }
                }
            } catch (Exception ex) {
                log.error("机台修改错误", ex);
                result.setSuccess(false);
                result.setMsg("机台修改错误");
            }
        }
        if ("doDelete".equals(action)) {
            try {
                Long poid = Utils.parseLong(id, 0L);
                if (poid == 0L) {
                    result.setSuccess(false);
                    result.setMsg("机台ID不能为空");
                }
                if (result.isSuccess()) {
                    SMachine sMachine = new SMachine();
                    sMachine.setId(poid);
                    sMachine.setModifyTime(new Date());
                    sMachine.setModifier(getSessionUsername(request));
                    sMachine.setFlag(false);
                    sMachineService.update(sMachine);
                    log.info("机台删除");
                }
            } catch (Exception ex) {
                log.error("机台删除错误", ex);
                result.setSuccess(false);
                result.setMsg("机台删除错误");
            }
        }
        log.info(JSONUtil.object2json(result));
        response.getWriter().write(JSONUtil.object2json(result));
    }


    /**
     *
     * @param sDeviceTechList
     * @param machid
     * @return
     */
    public boolean insertMachineTech(List<SDeviceTech> sDeviceTechList, Long machid) {
        try {
            List<SMachineTech> list = new ArrayList<>();
            for (SDeviceTech sDeviceTech : sDeviceTechList) {
                SMachineTech sMachineTech = new SMachineTech();
                sMachineTech.setMachid(machid);
                sMachineTech.setCval(sDeviceTech.getMinval());
                sMachineTech.setDtid(sDeviceTech.getId());
                list.add(sMachineTech);
            }
            sMachineTechService.insertMachineTechBatch(list);
            log.info("机台技术参数参入成功");
            return true;
        }
        catch (Exception ex) {
            log.error("机台技术参数参入错误", ex);
        }
        return false;
    }


}
